var express = require('express');
var router = express.Router();
const WebSocket = require('ws');
const app = express();
const http = require('http');
const socketIo = require('socket.io');
var { outpatient, prescription, surgery, group } = require('../model/model')
const server = http.createServer(app);

// 创建 Socket.IO 服务器并与 HTTP 服务器关联
const io = socketIo(server, {
    cors: {
        origin: "http://localhost:5173", // 允许来自该地址的请求
        methods: ["GET", "POST"], // 允许的 HTTP 方法
        allowedHeaders: ["my-custom-header"], // 允许的自定义头部
        credentials: true // 如果需要携带认证信息，可以设置为 true
    }
});
// 监听客户端连接
const formatData = (data) => {
    return data.map(item => ({
        ...item.toObject(),
        _id: item._id.toString()
    }));
};
io.on('connection', (socket) => {
    console.log('A user connected');
    let nums = 0
    const fetchDataAndSend = async () => {
        try {
            // 查询数据库中的所有 Item
            let ols = formatData(await outpatient.find().sort({ _id: 1 }))
            let pls = formatData(await prescription.find().sort({ _id: 1 }))
            let sls = formatData(await surgery.find().sort({ _id: 1 }))
            let gls = formatData(await group.find().sort({ _id: 1 }))
            const items = {
                ols,
                pls,
                sls,
                gls
            }
            // 发送数据给客户端
            socket.emit('items', items); // 'items' 是前端监听的事件名称
        } catch (error) {
            console.error('Error fetching data from database:', error);
        }
    };


    fetchDataAndSend();// 初次连接时立即发送数据
    // 发送消息给连接的客户端（模拟轮询效果，每5秒发送一次）
    const intervalId = setInterval(() => {
        // 调用获取数据的函数
        // console.log(1);
        fetchDataAndSend();
        const message = `123`;
        socket.emit('message', message);
    }, 5000);

    // 监听断开连接
    socket.on('disconnect', () => {
        console.log('User disconnected');
        clearInterval(intervalId); // 清除定时器
    });
});

// 启动服务器
const port = 3003;
server.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});



module.exports = router;